<template>
  <el-drawer
    :title="title"
    :visible.sync="dialogFormVisible"
    size="500px"
    @close="close"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model.trim="formData.className"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script>
  import { createClass, updateClass } from '@/apis/class'

  export default {
    name: 'ClassEditor',
    data() {
      return {
        formData: {
          className: null,
        },
        rules: {
          className: [
            { required: true, trigger: 'change', message: '请输入班级名称' },
          ],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    created() {},
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.formData = Object.assign({}, row)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['formRef'].resetFields()
        this.formData = this.$options.data().formData
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['formRef'].validate(async (valid) => {
          if (valid) {
            try {
              let actionFn
              if (this.formData.id) {
                actionFn = updateClass
              } else {
                actionFn = createClass
              }
              await actionFn(this.formData)

              this.$baseMessage('操作成功', 'success')
              this.$emit('on-success')
              this.close()
            } catch (e) {
              this.$baseMessage('操作失败', 'error')
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
